package kvraft

import (
	`sync`
)

type KVDB struct {
	m  map[string]string
	mu sync.Mutex
	me int
}

func (db *KVDB) Init(me int) {
	db.m = make(map[string]string)
	db.me = me
}

func (db *KVDB) Get(key string) *generalReply {
	db.mu.Lock()
	defer db.mu.Unlock()
	v, ok := db.m[key]
	DPrintf("[%d] GET: key: %s, value: %s, exist: %t", db.me, key, v, ok)
	if !ok {
		return &generalReply{ErrNoKey, ""}
	}
	return &generalReply{OK, v}
}

func (db *KVDB) Put(key string, value string) *generalReply {
	db.mu.Lock()
	defer db.mu.Unlock()
	DPrintf("[%d] PUT: key: %s, value: %s", db.me, key, value)
	db.m[key] = value
	return &generalReply{OK, value}
}

func (db *KVDB) Append(key, value string) *generalReply {
	db.mu.Lock()
	defer db.mu.Unlock()
	if v, ok := db.m[key]; !ok {
		DPrintf("[%d] APPEND: key: %s, value: %s, exist: %t", db.me, key, value, ok)
		db.m[key] = value
	} else {
		DPrintf("[%d] APPEND: key: %s, value: %s, exist: %t", db.me, key, value, ok)
		db.m[key] = v + value
	}

	return &generalReply{OK, db.m[key]}
}
